/**
 * 渠道关联帐号复选框选择组件
 *
 * 使用示例:
 * Model: { selected_ids: ko.observable(), user_count: ko.observable() }
 * View: <group-user-checkbox-list params="value: selected_ids, count: user_count, type: 'vip|user', selected_func: 'function'" />
 */
ko.components.register('group-user-checkbox-list', {
  viewModel: function (params) {
    var self = this;

    this.silent = false;
    this.accounts = ko.observableArray();
    this.readonly = params.readonly || false;
    // vip: vip_group_user, user: group_user
    this.type = params.type || 'user';

    this.selectAll = function () {
      this.silent = true;

      _.each(this.accounts(), function (it) {
        it.selected(true);
      });

      this.notifyChanges();
      this.silent = false;
    };

    this.selectNone = function () {
      this.silent = true;

      _.each(this.accounts(), function (it) {
        it.selected(false);
      });

      this.notifyChanges();
      this.silent = false;
    };

    this.notifyChanges = function () {
      var ids = [];

      _.each(this.accounts(), function (it) {
        if (it.selected()) {
          ids.push(parseInt(it.id(), 10));
        }
      });

      params.value(ids);
    };

    // init
    var initialValues = ko.unwrap(params.value());

    // 处理外部导致的 value 变化
    if (params.value && params.value.subscribe) {
      params.value.subscribe(function (ids) {
        ids = ids || [];

        // 若非 silent 则说明是外部触发的
        if (!self.silent) {
          _.each(self.accounts(), function (it) {
            if (ids.indexOf(it.id()) < 0) {
              it.selected(false);
            } else {
              it.selected(true);
            }
          })
        }
      });
    }
	/**
    $.get('/backend/users/api_get_group_users?type=' + ko.unwrap(self.type))
      .then(function (res) {
        _.each(res.data, function (it) {
          if (params.selected_func) {
            it.selected = params.selected_func(it);
          } else {
            it.selected = _.indexOf(initialValues, it.id) >= 0;
          }

          var item = ko.mapping.fromJS(it);

          item.selected.subscribe(function () {
            if (!self.silent) {
              self.notifyChanges();
            }
          });

          self.accounts.push(item);
        });

        if (params.count) {
          params.count(res.data.length);
        }
      });
	***/
  },
  template:
    '<div class="group-user-checkbox-list">' +
      '<div class="actions">' +
        '<a href="javascript:;" data-bind="click: selectAll">全选</a>' +
        '<a href="javascript:;" data-bind="click: selectNone">全不选</a>' +
      '</div>' +
      '<div class="checkbox-list" data-bind="foreach: accounts">' +
        '<label class="checkbox-inline">' +
          '<input type="checkbox" data-bind="checked: selected, disable: $parent.readonly" /> <span data-bind="text: nickname"></span>' +
        '</label>' +
      '</div>' +
    '</div>'
});